package com.cafuc.discipline.service.impl;

import com.cafuc.discipline.dao.FileDao;
import com.cafuc.discipline.entity.FileInfo;
import com.cafuc.discipline.respone.Result;
import com.cafuc.discipline.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author Mete
 * @createTime 2023/3/15 10:38
 * @description 附件相关操作
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Resource
    private FileDao filedao;

    /*文件存储路径*/
    @Value("${file.path}")
    private String path;

    /**
     * @Description:文件上传操作
     * @Auther: Mete
     * @Date: 2023/3/16
     */
    @Override
    public Result UploadFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws Exception {
        if(file.isEmpty()){
            return Result.failure("文件为空");
        }
        String fileName = file.getOriginalFilename(); //下载的文件名
        String fileType = file.getContentType();//获取文件类型，用于判断文件上传类型控制
        byte[] fileSize = file.getBytes();
        /*构建文件新增信息实体*/
        FileInfo fileinfo = new FileInfo();
        fileinfo.setFile_name(fileName);
        fileinfo.setFile_url(path+fileName);

        //执行插入文件信息后返回自增id到fileInfo
        boolean isOk = filedao.insertFile(fileinfo);

        //插入文件信息
        if(isOk){
            //SpringBoot封装的方式保存文件    开始
            file.transferTo(new File(path+fileName));
            //SpringBoot封装的方式保存文件    结束
            //返回文件记录id
            return Result.success(fileinfo.getId());
        }

        return Result.failure("失败");
    }
}
